


function getList() {
	// $.ajax({})
	$(".loading").css("display", "flex")
	$.get("http://120.27.209.174:1010/api/v1/bmi", function(res) {
		$(".loading").css("display", "none")
		
		$("#list").empty()
		
		if(res.length === 0) {
			$("#list").append(`<tr>
				<td colspan="7" style="text-align: center;">暂无数据</td>
			</tr>`)
		} else {
			$.each(res, function(index, item) {
				$(`
					<tr>
						<td>${index+1}</td>
						<td>${item.created_at}</td>
						<td>${item.height}</td>
						<td>${item.weight}</td>
						<td>${item.bmi}</td>
						<td>${item.status}</td>
						<td>
							<a data-id="${item.id}" href="javascript:void(0)">删除</a>
						</td>
					</tr>
				`).appendTo("#list")
			})
		}
	})
}

getList()

$(".form button").on("click", function() {
	const $height = $("[name=height]")
	const $weight = $("[name=weight]")
	const numReg = /^[0-9]*$/
	if ($height.val() === "" || $weight.val() === "") {
		alert("不能为空")
	} else if(!numReg.test($height.val()) || !numReg.test($weight.val())) {
		alert("输入正确的身高体重")
	} else {
		$.post("http://120.27.209.174:1010/api/v1/bmi", {
			height: $height.val(),
			weight: $weight.val()
		}, function(res) {
			getList()
		})	
	}
})

// console.log($("#list tr a"))
// 事件委托
$("#list").on("click", "tr a",function () {
	// console.log($(this).attr("data-id"))
	const id = $(this).data("id")
	if (confirm("确定删除？")) {
		$.ajax({
			method: "DELETE",
			url: `http://120.27.209.174:1010/api/v1/bmi/${id}`,
			success(res) {
				if (res == 1) {
					getList()
				}
			}
		})
	}
})

